var express = require('express');
var router = express.Router();
const {User,Laboratory,Equipment} = require('../../models')
const {success,failure} = require('../../util/requestResult')
const {NotFoundError,BadRequestError,UnauthorizedError,AlreadyExistsError,SequelizeValidateError} = require('../../util/errors')
// 查询条件限制
const condition = {
    include:[
        {
            model:Equipment,
            as:'Equipments',
            attributes:['id','equipmentName','isApplyBook']
        }
    ]
}
// 查询所有实验室
router.get('/',async function(req,res,next){
    try {
        let laboratory = await Laboratory.findAll(condition)
        success(res,'查询所有实验室成功',laboratory)
    } catch (error) {
        failure(res,error)
    }

})

// 按id查找实验室
router.get('/:id',async function(req,res,next){
    try {
        let laboratory = await getlaboratory(req,true)
        success(res,`查询id为${req.params.id}的实验室成功`,laboratory)
    } catch (error) {
        failure(res,error)
    }

})

// 新增实验室
router.post('/',async function(req,res,next){
    try {
        let laboratoryInfo = filterBody(req)
        let createdLaboratory = await Laboratory.create(laboratoryInfo)
        success(res,'创建实验室成功',createdLaboratory,201)
    } catch (error) {
        failure(res,error)
    }

})

// 更新实验室
router.put('/:id',async function(req,res,next){
    try {
        let laboratoryInfo = filterBody(req)
        let laboratory = await getlaboratory(req)
        await laboratory.update(laboratoryInfo)
        success(res,`更新id为${req.params.id}实验室成功`,laboratory)
    } catch (error) {
        failure(res,error)
    }

})


// 删除实验室
router.delete('/:id',async function(req,res,next){
    try {
        let laboratory = await getlaboratory(req)
        await laboratory.destroy()
        success(res,`删除id为${req.params.id}实验室成功`)
    } catch (error) {
        failure(res,error)
    }

})


function filterBody(req){
    let {laboratoryName,openTime,closeTime,isApplyBook,max} = req.body
    return {laboratoryName,openTime,closeTime,isApplyBook,max}
}


async function getlaboratory(req,isCondition){
    const {id} = req.params
    let laboratory
    laboratory = await Laboratory.findByPk(id,isCondition?condition:{})
    if(!laboratory)
        throw new NotFoundError(`未查询到id为${id}的实验室`)
    return laboratory
}

module.exports = router